import React, { Component } from 'react';
import classnames from 'classnames';
import { toJS } from 'mobx';
import { withRouter, Route } from 'react-router-dom';
import { inject, observer } from 'mobx-react';
import { List, Button, Progress, Avatar, Bubble, Tools, Icon, PhotoSwipe } from 'weaver-mobile';
import { RouteLayout, ListPage } from 'weaver-mobile-page';
import { renderLoading, renderNotExist } from '../util';
import { resetEmElement, controlEmTopNav, doInitEmSDK } from '../util/emSDK';
import PersonList from './PersonList';

const getLabel = Tools.getLabel;
const Normal = ListPage.Normal;
@withRouter
@inject('voteStore', 'listStore')
@observer
class Vote extends Component {
  constructor(props) {
    super(props)
    this.prefixCls = 'group-vote-voting'
  }
  
  componentDidMount () {
    const { location: { pathname }, match: { params }, voteStore } = this.props;
    const { setStoreState, viewGroupVote, initLayout } = voteStore;
    
    //设置EM客户端顶部头信息
    doInitEmSDK();
    controlEmTopNav({ title: '投票详情' })
    
    setStoreState({voteId: params.id, path: pathname}, () => {
      initLayout();
      if (window.em) {
        window.em.ready(() => {
          let res = window.em.checkJsApi("getTargetInfo");
          if (res) {
            window.em.getTargetInfo({
              success: function(res) {
                let params = {groupid: res.targetId, isgroup: res.targetType};
                setStoreState(params);
                viewGroupVote({groupid: res.targetId});
              },
              fail: function(res) {
                Bubble.error(res.errMsg || '方法请求失败')
              }
            })
          }
        })
      } else {
        viewGroupVote();
      }
    })
  }
  
  componentWillUnmount() {
    const { voteStore: { clearSelect, clear } } = this.props;
    resetEmElement();
    clearSelect();
    clear();
  }

  getTemplate = () => {
    const newTemp = {
      default: [{
        key: 'col_1',
        render: (data) => {
          return (
            <div className={`${this.prefixCls}-option`} key={data.optionid}>
              <div className={`${this.prefixCls}-option-lable`}>{data.optioncontent}</div>
              {
                data.optionimg !== '' && (
                  <div className={`${this.prefixCls}-option-imgs`}>
                    { data.optionimg.split(',').map((item,index) => (<img alt='' src={item} key={index} onClick={(e) => this.onImgClick(e, item)}/>)) }
                  </div>
                )
              }
            </div>
          );
        },
      }],
    };
    return newTemp;
  }

  getEndTemplate = () => {
    const newTemp = {
      default: [{
        key: 'col_1',
        render: (data) => {
          return (
            <div key={data.optionid} className={`${this.prefixCls}-container-optionItem`}>
              <div className='title'>
                <span className='content'>
                  {Number(data.voteThisOption) === 1 && (<Icon type='blog-yiguanzhu' size='sm' />)}
                  {data.optioncontent}
                </span>
                <span className='count'>{data.votecount}{getLabel('18607','票')}</span>
              </div>
              <Progress percent={Number(data.votepercent)} position='normal' style={{ height: 2, marginTop: 8 }}/>
              {
                data.optionimg && data.optionimg !== '' && (
                  <div className='images'>
                    { data.optionimg.split(',').map((item,index) => (<img alt='' src={item} key={index} onClick={(e) => this.onImgClick(e, item)}/>)) }
                  </div>
                )
              }
            </div>
          );
        },
      }],
    };
    return newTemp;
  }

  renderContainer = (data) => {
    const { history, voteStore: { voteOptionList, personListLayout } } = this.props;
    if (data.votestatus === '0' && data.hasvote === '0') { // 未结束，自己未投票
      return (
        <Normal
          store={voteOptionList}
          showCheck
          rowKey='optionid'
          template={{ default: '' }}
          getTemplate={this.getTemplate}
          multipleCheck={data.choosemodel === '1'}
        />
      )
    } else if (data.votestatus === '1' || data.hasvote === '1') { // 未结束，自己已投票 || 投票已结束
      return (
        <Normal
          store={voteOptionList}
          rowKey='optionid'
          template={{ default: '' }}
          getTemplate={this.getEndTemplate}
          onRowClick={(record) => {
            if (data.voteprivacy === '1') {
              history.push(`${personListLayout.path}/2?optionid=${record.optionid}`)
            }
          }}
        />
      )
    }
  }

  renderPerson = (label, person, data, params) => {
    const { history, voteStore: { personListLayout } } = this.props;
    if (data) {
      return (
        <List className={`${this.prefixCls}-options-item`}>
          <List.Item 
            arrow={(person && person.length > 0) ? 'horizontal' : ''}
            onClick={() => {
              if (person && person.length > 0) {
                history.push(`${personListLayout.path}/${params}`)
              }
            }}
          >{label}</List.Item>
          <List.Item>
            {
              (person && person.length > 0) && person.map(item => (
                <div className={`${this.prefixCls}-options-item-persons`} key={item.voteuserid} onClick={() => this.openHrmCard(item.voteuserid)}>
                  <Avatar userId={item.voteuserid} url={item.messagerurl} name={item.voteusername}/>
                  <div className={'name'}>{item.voteusername}</div>
                </div>
              ))
            }
          </List.Item>
        </List>
      )
    }
  }

  openHrmCard = (id) => {
    if (window.em && (typeof window.em.checkJsApi === 'function') && window.em.checkJsApi('openLink')) {
      window.em.openLink({
        url: `/spa/hrm/static4mobile/index.html#/resourceInfo/${id}`,
        openType: 2,
        sysId: window.localStorage.emobile_ec_id,
      });
    }
  }

  onImgClick = (e, file) => {
    e.stopPropagation();
    e.preventDefault();

    const { voteStore: { imgArr } } = this.props
    let targetIndex = this.getArrIndex(imgArr, file)
    PhotoSwipe.showImage(imgArr, targetIndex);
  }

  getArrIndex = (Arr, url) => {
    let aimIndex = 0;
    Arr.map((v, index) => {
      if ((url.indexOf(toJS(v).url) > -1 || url === toJS(v).url)) {
        aimIndex = index;
      }
      return 0;
    })
    return aimIndex;
  }
  
  render () {
    const { voteStore: { dataInfo, onVote, voteLoading, personListLayout, voteId, viewRight, voteOptionList, saveLoading }, listStore: { updateListData } } = this.props;
    const data = toJS(dataInfo);
    const select = toJS(voteOptionList.selectedRowKeys);
    const votedCls = classnames({
      [`${this.prefixCls}-box`]: true,
      'hasBtn': (data.votestatus === '0' && data.hasvote === '0'),
    });
    const optionText = data.maxvoteoption === '0' ? `(${getLabel('32499','不限制')})` : `(${getLabel('516177','最多可选')}${data.maxvoteoption}${getLabel('26302','项')})`;
    let child = null;
    if (voteLoading) {
      child = renderLoading;
    } else if (!viewRight) {
      child = renderNotExist();
    } else {
      let curCls = 'group-vote-list-item';
      child = (
        <div className={this.prefixCls}>
          <div className={votedCls}>
            <div className={`${this.prefixCls}-header`}>
              <div className={`${curCls}-header`}>
                <Avatar userId={data.createrid} url={data.messagerurlspan || data.messageurl || ''} name={data.createridspan}/>
                <div className={`${curCls}-header-userInfo`}>
                  <div className='user'>
                    <div>
                      <a className='createName' onClick={() => this.openHrmCard(data.createrid)}>{data.createridspan || data.creatername}</a>
                      <span className='department'>{data.departmentnamespan || data.createrDept}</span>
                    </div>
                    {data.votestatus === '0' ? <span className='state ing'>{getLabel('1960','进行中')}</span> : <span className='state end'>{getLabel('22348','已结束')}</span>}
                  </div>
                  <span className='createTime'>{`${data.createdatespan || data.createdate} ${data.createtimespan || data.createtime}`}</span>
                </div>
              </div>
            </div>
            <div className={`${this.prefixCls}-theme`}>
              <div className={`${this.prefixCls}-theme-detail`} dangerouslySetInnerHTML={{__html: data.votetheme}}/>
              {
                data.themepicsrc &&
                <div className={`${this.prefixCls}-theme-image`} onClick={(e) => this.onImgClick(e, data.themepicsrc)}>
                  <img alt='' src={data.themepicsrc}/>
                </div>
              }
            </div>
            <div className={`${this.prefixCls}-container`} style={data.themepicsrc ? {}: { marginTop: 10 } }>
              <div className={`${this.prefixCls}-container-title`}>
                <span>{data.choosemodelshow} {data.choosemodel === '1' && optionText}</span>
                {(data.votestatus === '1' || data.hasvote === '1') && <span>{getLabel('500891','已投')}{data.votetotalcount}{getLabel('18607','票')}</span>}
              </div>
              { this.renderContainer(toJS(dataInfo)) }
              <div className={`${this.prefixCls}-container-endTime`}>{`${getLabel('18111','截止时间：')} ${data.enddate} ${data.endtime}`}</div>
              { data.showremindString && (
                <div className={`${this.prefixCls}-container-endTime`}>{data.showremindString}</div>
              )}
            </div>
            {
              data.voteprivacy === '1'&& 
              <div className={`${this.prefixCls}-options`}>
                {this.renderPerson(data.votelabel, data.havevotedpersons, data, '0')}
                {this.renderPerson(data.notvotelabel, data.havenotvotedpersons, data, '1')}
              </div>
            }
          </div>
          {
            (data.votestatus === '0' && data.hasvote === '0') ? (
              <Button 
                type='primary' 
                disabled={select.length === 0 || saveLoading} 
                loading={saveLoading}
                onClick={() => {
                  onVote('', () => updateListData(voteId, { hasvotespan: '1' }))
                }}
              >{getLabel('126097','投票')}</Button>
            ) : null
          }
          <Route
            key={personListLayout.id}
            path={`${personListLayout.path}/:usertype`}
            render={() => (
              <RouteLayout>
                <div key="personlist" className="wm-route-layout">
                  <PersonList />
                </div>
              </RouteLayout>
            )}
          />
        </div>
      )
    }
    return (
      <RouteLayout>
        <div key="voted" className="wm-route-layout">
          { child }
        </div>
      </RouteLayout>
    )
  }
}

export default Vote